package tessk.controller;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;

import tessk.common.def.JsonResult;
import tessk.common.def.ResultEnum;
import tessk.config.Audience;
import tessk.entity.AccessToken;
import tessk.entity.User;
import tessk.jwt.JwtHelper;
import tessk.mapper.UserMapper;

@RestController  
public class OauthController {
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private Audience audienceEntity;

	
	@GetMapping("oauth/login")
	public Object getAccessToken(@RequestParam String username,@RequestParam String pwd){
		if(StringUtils.isEmpty(username) || StringUtils.isEmpty(pwd)){
			return new JsonResult(ResultEnum.USER_INFO_ERROR);
		}
		User findUser = new User();
		findUser.setUsername(username);
		User user = userMapper.queryInfoByUserName(username);
		if(user == null){
			return new JsonResult(ResultEnum.USER_INFO_ERROR);
		}else {
			String passwd = new SimpleHash("SHA-1", username, pwd).toString(); // 密码加密
			if(!passwd.equals(user.getPassword())){
				return new JsonResult(ResultEnum.USER_INFO_ERROR); 
			}
		}
		String accessToken = JwtHelper.createJWT(user.getName(), user.getUserId(), audienceEntity.getName(), audienceEntity.getDefaultExpire(), audienceEntity.getBase64Secret());
		AccessToken accessTokenEntity = new AccessToken();
		accessTokenEntity.setToken(accessToken);
		accessTokenEntity.setExpiresIn(audienceEntity.getDefaultExpire());
		return new JsonResult(ResultEnum.SUCCESS,accessTokenEntity);
	}
}
